package com.dbConnection;

import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Connection;
import java.util.ArrayList;

public class theConnection {
	Connection conn = null;
	Statement statement = null;
	ResultSet results = null;
	
	String Driver = "com.mysql.jdbc.Driver";
	String url = "jdbc:mysql://academic-mysql.cc.gatech.edu/cs4400_group40";
	
	String username;

	public theConnection(){
		try{ 
		      Class.forName(Driver).newInstance(); 
		      conn = DriverManager.getConnection(url,"cs4400_group40", "wB8qjsjr"); 
		      if(!conn.isClosed()) 
		        System.out.println("Successfully connected to " + 
		          "MySQL server using TCP/IP..."); 
		    } 
		catch(Exception e) { 
		     // System.err.println("Exception: " + e.getMessage());
		      e.printStackTrace();
		    } 
	}
	
	public void close(){
		if(conn != null)
			try {
				conn.close();
				System.out.println("SQL Server Connection Closed");
			} catch (SQLException e) {
				e.printStackTrace();
			}
	}
	
	public void askDB(String query){
		try {
			statement = conn.createStatement();
			results = statement.executeQuery(query);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	public boolean updateDB(String query) throws SQLException{
		try{
			statement = conn.createStatement();
			statement.execute(query);
			return true;
		}catch(SQLException e){
			e.printStackTrace();
			throw new SQLException();
		}
		
	}
	public ArrayList<String> getLastQuery(int columns) throws SQLException{
		ArrayList<String> answers = new ArrayList<String>();
		int i = 0;
		int j = 0;
		while(!results.isAfterLast()){
			while (j<columns){
				answers.add(results.getString(j));
				i++;
				j++;
			}
			j = 0;
			results.next();			
		}
		return answers;
	}
	
	public void prepare(String query,String... params) throws SQLException{
		PreparedStatement pstatement = conn.prepareStatement(query);
		int i = 0;
		for(String s: params){
			try{
				pstatement.setString(i, s);
				//set string question marks
				
				results = pstatement.executeQuery();
			}
			catch(SQLException e){
				throw new SQLException();
			}
			i++;
		}
		
	}
	
	public void setUser(String username){
		this.username = username;
	}
	
	public String getUser(){
		return username;
		
	}
}//end class
	 

